package cn.xinfei.xdecision.feign;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

@Slf4j
public class CacheInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        long t1 = 0;
        //1.请求前--打印请求信息
        t1 = System.nanoTime();
        HttpUrl url = request.url();
        log.info(String.format("Sending request %s on conn:%s header: %n %s", url, chain.connection(), request.headers()));
        Response originResponse = chain.proceed(request);

        //3.网络响应后--打印响应信息
        long t2 = System.nanoTime();
//        ResponseBody responseBody = originResponse.peekBody(1024 * 1024);
//        System.out.println("responseBody====:"+  responseBody.string());
        log.info(String.format("Received response for %s in %.1fms%n%s",url, (t2 - t1) / 1e6d, originResponse.headers()));

        //设置缓存时间为60秒，并移除了pragma消息头，移除它的原因是因为pragma也是控制缓存的一个消息头属性
//        return originResponse.newBuilder()
//                .removeHeader("pragma")
//                .header("Cache-Control", "max-age=600")
//                .build();
        return originResponse;
    }
}
